import React from 'react'
import './App.scss'
import Router from './router'
import { extend } from 'lodash'
import {
  useLocation,
  Navigate,
  useNavigate,
  useSearchParams,
} from 'react-router-dom'
import { message } from 'antd'
import { l } from './utils/storage'

function App() {
  return <Router></Router>
}

function withLogin(Comp: React.FC) {
  const whiteList = ['/login']
  return () => {
    const location = useLocation()
    const pathname = location.pathname
    const [searchParams] = useSearchParams()
    const from = searchParams.get('from')
    const token = localStorage.getItem('token')
    // 当前访问的是白名单页面
    if (whiteList.includes(pathname)) {
      if (token) {
        message.success('当前用户已经登录， 无需在此登录')
        if (from) {
          return <Navigate to={from}></Navigate>
        } else {
          return <Navigate to="/"></Navigate>
        }
      } else {
        return <Comp></Comp>
      }
    } else {
      // 当前访问的非白名单页面
      if (token) return <Comp></Comp>
      else {
        message.success('用户为登录， 请登录后访问')
        return <Navigate to="/login"></Navigate>
      }
    }
  }
}

export function withPrivateRouter(Comp: React.FC, roles?: string[]) {
  return () => {
    if (!roles) {
      return <Comp></Comp>
    } else {
      const userInfo = l.getItem('userInfo') || {}
      const role = userInfo.role
      if (roles.includes(role)) {
        return <Comp></Comp>
      } else {
        return <div>403, 没有访问权限，请联系管理员</div>
      }
    }
  }
}

export default withLogin(App)
